package com.lvcoding.sec3.secdemo3.util;


import com.lvcoding.sec3.secdemo3.config.SysConfig;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.experimental.UtilityClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@Component
public class JwtUtil {

    @Autowired
    private SysConfig sysConfig;

    private static SysConfig staticSysConfig = null;

    @PostConstruct
    public void init() {
        staticSysConfig = sysConfig;
    }

    // 秘钥,至少32个字符
//    private String secret = sysConfig.getToken().getSecret();

//    private long expire = sysConfig.getToken().getExpireIn();

    public static String createToken(Map<String, Object> map) {

        return Jwts.builder()
                .addClaims(map)
                .signWith(getKey())
                .setExpiration(new Date(System.currentTimeMillis() + staticSysConfig.getToken().getExpireIn()))
                .compact();
    }

    public static Map<String, Object> parseToken(String token) {
        return (Map<String, Object>) Jwts.parserBuilder()
                .setSigningKey(getKey())
                .build()
                .parse(token)
                .getBody();
    }

    public static boolean checkToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(getKey())
                    .build()
                    .parse(token)
                    .getBody();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private static Key getKey() {
        return Keys.hmacShaKeyFor(staticSysConfig.getToken().getSecret().getBytes());
    }
}
